//
//  EWEAudio.m
//  Auscultation
//
//  Created by 来 on 2020/12/11.
//

#import "EWEAudio.h"
#import "EWEHeader.h"

@implementation EWEAudio

// pcm转wav
+ (BOOL)pcm2Wav:(NSString *)pcmPath outPath:(NSString *)outPath isDeleteSourchFile:(BOOL)isDelete {
    NSData *data = [NSData dataWithContentsOfFile:pcmPath];
    BOOL isSuccess = [[self writeWavHead:data] writeToFile:outPath atomically:YES];
    if (isSuccess && isDelete) {
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:pcmPath error:nil];
    }
    return isSuccess;
}

//获取录音设置
+ (NSDictionary*)GetAudioRecorderSettingDict{
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   [NSNumber numberWithFloat: LGF_SampleRate],AVSampleRateKey, //采样率
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   [NSNumber numberWithInt:LGF_SampleBits],AVLinearPCMBitDepthKey,//采样位数 默认 16
                                   [NSNumber numberWithInt: LGF_NumOfChannels], AVNumberOfChannelsKey,//通道的数目
                                   nil];
    return recordSetting;
}

// 为pcm文件写入wav头
+ (NSData*)writeWavHead:(NSData *)audioData {
    long sampleRate = [[self GetAudioRecorderSettingDict][AVSampleRateKey] longValue];
    long numOfChannelsKey = [[self GetAudioRecorderSettingDict][AVNumberOfChannelsKey] longValue];
    Byte waveHead[44];
    waveHead[0] = 'R';
    waveHead[1] = 'I';
    waveHead[2] = 'F';
    waveHead[3] = 'F';
    
    long totalDatalength = [audioData length] + 36;
    waveHead[4] = (Byte)(totalDatalength & 0xff);
    waveHead[5] = (Byte)((totalDatalength >> 8) & 0xff);
    waveHead[6] = (Byte)((totalDatalength >> 16) & 0xff);
    waveHead[7] = (Byte)((totalDatalength >> 24) & 0xff);
    
    waveHead[8] = 'W';
    waveHead[9] = 'A';
    waveHead[10] = 'V';
    waveHead[11] = 'E';
    
    waveHead[12] = 'f';
    waveHead[13] = 'm';
    waveHead[14] = 't';
    waveHead[15] = ' ';
    
    waveHead[16] = 16;  //size of 'fmt '
    waveHead[17] = 0;
    waveHead[18] = 0;
    waveHead[19] = 0;
    
    waveHead[20] = 1;   //format
    waveHead[21] = 0;
    
    waveHead[22] = numOfChannelsKey;   //chanel
    waveHead[23] = 0;
    
    waveHead[24] = (Byte)(sampleRate & 0xff);
    waveHead[25] = (Byte)((sampleRate >> 8) & 0xff);
    waveHead[26] = (Byte)((sampleRate >> 16) & 0xff);
    waveHead[27] = (Byte)((sampleRate >> 24) & 0xff);
    
    long byteRate = sampleRate * numOfChannelsKey * (16 >> 3);
    waveHead[28] = (Byte)(byteRate & 0xff);
    waveHead[29] = (Byte)((byteRate >> 8) & 0xff);
    waveHead[30] = (Byte)((byteRate >> 16) & 0xff);
    waveHead[31] = (Byte)((byteRate >> 24) & 0xff);
    
    waveHead[32] = 2*(16 >> 3);
    waveHead[33] = 0;
    
    waveHead[34] = 16;
    waveHead[35] = 0;
    
    waveHead[36] = 'd';
    waveHead[37] = 'a';
    waveHead[38] = 't';
    waveHead[39] = 'a';
    
    long totalAudiolength = [audioData length];
    
    waveHead[40] = (Byte)(totalAudiolength & 0xff);
    waveHead[41] = (Byte)((totalAudiolength >> 8) & 0xff);
    waveHead[42] = (Byte)((totalAudiolength >> 16) & 0xff);
    waveHead[43] = (Byte)((totalAudiolength >> 24) & 0xff);
    
    NSMutableData *pcmData = [[NSMutableData alloc]initWithBytes:&waveHead length:sizeof(waveHead)];
    [pcmData appendData:audioData];
    
    return pcmData;
    
}

+ (NSData*)dataForHexString:(NSString*)hexString

{

      if (hexString == nil) {

        return nil;

    }

    const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];

    NSMutableData* data = [NSMutableData data];

    while (*ch) {

        if (*ch == ' ') {

            continue;

        }

        char byte = 0;

        if ('0' <= *ch && *ch <= '9') {

            byte = *ch - '0';

        }

        else if ('a' <= *ch && *ch <= 'f') {

            byte = *ch - 'a' + 10;

        }

        else if ('A' <= *ch && *ch <= 'F') {

            byte = *ch - 'A' + 10;

        }

        ch++;

        byte = byte << 4;

        if (*ch) {

            if ('0' <= *ch && *ch <= '9') {

                byte += *ch - '0';

            } else if ('a' <= *ch && *ch <= 'f') {

                byte += *ch - 'a' + 10;

            }

            else if('A' <= *ch && *ch <= 'F')

            {

                byte += *ch - 'A' + 10;

            }

            ch++;

        }

          [data appendBytes:&byte length:1];

    }

    return data;

}

@end
